﻿<%@ Page Language="C#" %>

<%@ Import Namespace="System.IO" %>

<%
    try
    {
        var filePath = Request.QueryString["filePath"];
        var index = filePath.IndexOf('/');

        var objfolderName = filePath.Substring(0, index);

        var pkId = filePath.Substring(filePath.LastIndexOf('/') + 1);
        var subFolder = filePath.Substring(index + 1);

        string filePhysicalPath = Server.MapPath(String.Format("~/Files/{0}", filePath));
        ViewState["page_file_path"] = filePhysicalPath;
        if (!Directory.Exists(filePhysicalPath))//判断上传文件夹是否存在，若不存在，则创建
        {
            Directory.CreateDirectory(filePhysicalPath);//创建文件夹
        }
    }
    catch
    {
    }
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script type="text/javascript" src="Resources/dynamsoft.webtwain.initiate.js"></script>
<script type="text/javascript" src="Resources/dynamsoft.webtwain.config.js"></script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Title</title>
</head>
<body>
    <input type="button" value="扫描" onclick="AcquireImage();" />
    <input type="button" value="上传到文件服务器" onclick="UploadImage();" />
    <br />
    <div style="display: none">
        <label>
            <input type="radio" value="jpg" name="ImageType" id="imgTypejpeg" />JPEG</label>
        <label>
            <input type="radio" value="tif" name="ImageType" id="imgTypetiff" />TIFF</label>
        <label>
            <input type="radio" value="pdf" name="ImageType" id="imgTypepdf" checked="checked" />PDF</label>
    </div>



    <!-- dwtcontrolContainer is the default div id for Dynamic Web TWAIN control.
If you need to rename the id, you should also change the id in the dynamsoft.webtwain.config.js accordingly. -->
    <div id="dwtcontrolContainer"></div>
    <script type="text/javascript">
        Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); // Register OnWebTwainReady event. This event fires as soon as Dynamic Web TWAIN is initialized and ready to be used

        var DWObject;

        function Dynamsoft_OnReady() {
            DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
            //if (DWObject) {
            //    DWObject.RegisterEvent('OnPostAllTransfers', SaveWithFileDialog);
            //}
        }

        function AcquireImage() {
            if (DWObject) {
                DWObject.SelectSource();
                DWObject.OpenSource();
                DWObject.IfDisableSourceAfterAcquire = true;	// Scanner source will be disabled/closed automatically after the scan.
                DWObject.AcquireImage();
            }
        }



        // OnHttpUploadSuccess and OnHttpUploadFailure are callback functions.
        // OnHttpUploadSuccess is the callback function for successful uploads while OnHttpUploadFailure is for failed ones.
        function OnHttpUploadSuccess() {
            //console.log('successful');
            if (DWObject) {
                DWObject.RemoveAllImages();
            }
            alert("扫描上传成功!");
        }

        function OnHttpUploadFailure(errorCode, errorString, sHttpResponse) {
            //alert(errorString + sHttpResponse);
            alert("扫描上传出错!");
        }


        //Callback functions for async APIs
        function OnSuccess() {
            //console.log('successful');
            if (DWObject) {
                DWObject.RemoveAllImages();
            }
        }

        function OnFailure(errorCode, errorString) {
            //alert(errorString);
            alert("扫描上传出错!");
        }

        function UploadImage() {
            debugger;
            if (DWObject) {
                // If no image in buffer, return the function
                if (DWObject.HowManyImagesInBuffer == 0)
                    return;

                var strHTTPServer = location.hostname; //The name of the HTTP server. For example: "www.dynamsoft.com";
                var CurrentPathName = unescape(location.pathname);
                var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
                //var strActionPage = CurrentPath + "SaveToFile.aspx";

                var strActionPage = CurrentPath + "FileManager/SaveScanFilesToServer?filePath=<%= ViewState["page_file_path"].ToString().Replace(@"\",@"\\")%>";
                debugger;
                DWObject.IfSSL = false; // Set whether SSL is used
                DWObject.HTTPPort = location.port == "" ? 80 : location.port;

                var Digital = new Date();
                var uploadfilename = Digital.getMilliseconds(); // Uses milliseconds according to local time as the file name

                // Upload the image(s) to the server asynchronously
                if (document.getElementById("imgTypejpeg").checked == true) {
                    //If the current image is B&W
                    //1 is B&W, 8 is Gray, 24 is RGB
                    if (DWObject.GetImageBitDepth(DWObject.CurrentImageIndexInBuffer) == 1)
                        //If so, convert the image to Gray
                        DWObject.ConvertToGrayScale(DWObject.CurrentImageIndexInBuffer);
                    //Upload image in JPEG
                    DWObject.HTTPUploadThroughPost(strHTTPServer, DWObject.CurrentImageIndexInBuffer, strActionPage, uploadfilename + ".jpg", OnHttpUploadSuccess, OnHttpUploadFailure);
                }
                else if (document.getElementById("imgTypetiff").checked == true) {
                    DWObject.HTTPUploadAllThroughPostAsMultiPageTIFF(strHTTPServer, strActionPage, uploadfilename + ".tif", OnHttpUploadSuccess, OnHttpUploadFailure);
                }
                else if (document.getElementById("imgTypepdf").checked == true) {
                    DWObject.HTTPUploadAllThroughPostAsPDF(strHTTPServer, strActionPage, uploadfilename + ".pdf", OnHttpUploadSuccess, OnHttpUploadFailure);
                }
            }
        }
    </script>
</body>
</html>
